python loop function

49

# (initial,final but not included,gap)
for i in range(1, 10, 2):
  print(i)
  # output: 1,3,5,7,9

# (initial, final but not included)
for i in range(1, 4):
  print(i)
  # output: 1,2,3 note: 4 not included

for i in range(5):
  print(i)
  # output: 0,1,2,3,4 note: 5 not included

python = ["ml", "ai", "dl"]
for i in python:
  print(i)
  # output:  ml,ai,dl

# empty loop...if pass not used then it will return error
for i in range(1, 5):
  pass

# break out loop
for i in range(1, 5):
  if i == 3:
      break
  print(i)

# when you do not need to know the value of items use an underscore
for _ in range(1, 5):
  pass

# continue to the start of the loop
for i in range(10):
  if i == 3:  # skips if i is 3
      continue
  print(i)

# The else statement is only reached if the for loop
# has run all the way through without breaking
list = [99, 98, 97, 96, 95, 94]

for number in list:
  if number == 2:
      print("There is a 2 in the list")
      break
else:
  print("There are no 2's in the list")

num = 1

# while loop
while num <= 5:
  print(num)
  num += 1for i in range(1, 10, 2):  # (initial,final but not included,gap)
  print(i);
  # output: 1,3,5,7,9

for i in range(1, 4):  # (initial, final but not included)
  print(i);
  # output: 1,2,3 note: 4 not included

for i in range(5):
  print(i);
  # output: 0,1,2,3,4 note: 5 not included

python = ["ml", "ai", "dl"];
for i in python:
  print(i);
  # output:  ml,ai,dl

# empty loop...if pass not used then it will return error
for i in range(1, 5):
  pass;

# break out loop
for i in range(1, 5):
  if i == 3:
      break
  print(i)

# when you do not need to know the value of items use an underscore
for _ in range(1, 5):
  pass

# continue to the start of the loop
for i in range(10):
  if i == 3:  # skips if i is 3
      continue
  print(i)

# The else statement is only reached if the for loop
# has run all the way through without breaking
list = [99, 98, 97, 96, 95, 94]

for number in list:
  if number == 2:
      print("There is a 2 in the list")
      break
else:
  print("There are no 2's in the list")

num = 1

# while loop
while num <= 5:
  print(num)
  num

Comments

Submit
0 Comments